package 赎金信;
//给你两个字符串：ransomNote 和 magazine ，判断 ransomNote 能不能由 magazine 里面的字符构成。
//
//如果可以，返回 true ；否则返回 false 。
//
//magazine 中的每个字符只能在 ransomNote 中使用一次。
//
//
//
//示例 1：
//
//输入：ransomNote = "a", magazine = "b"
//输出：false

import java.util.Map;
import java.util.stream.Collectors;

public class Solution
{
    public static boolean canConstruct(String ransomNote, String magazine)
    {
        //哈希
        Map<Character, Long> map1 = ransomNote.chars().
                mapToObj(c -> (char) c).
                collect(
                        Collectors.groupingBy(c -> c, Collectors.counting())
                );
        Map<Character, Long> map2 = magazine.chars().mapToObj(c -> (char) c).collect(Collectors.groupingBy(c -> c, Collectors.counting()));

        boolean res = map1.entrySet().stream().allMatch(entry -> map2.containsKey(entry.getKey()) && (entry.getValue() <= map2.get(entry.getKey())));
        return res;
    }

    public static boolean canConstruct0(String ransomNote, String magazine)
    {
        if (ransomNote.length() > magazine.length())
            return false;
        int[] cnt = new int[26];
        for (char c : magazine.toCharArray())
        {
            //原料
            cnt[c - 'a']++;
        }
        for (char c : ransomNote.toCharArray())
        {
            //产品
            cnt[c - 'a']--;
            if (cnt[c - 'a'] < 0)
            {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args)
    {
        String ransomNote = "aa";
        String magazine = "aab";
        System.out.println(canConstruct0(ransomNote, magazine));
    }
}
